package org.crystalrange.files.web;

import java.util.List;

import org.crystalrange.files.model.FileType;
import org.crystalrange.files.service.FileTypeService;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zkplus.databind.AnnotateDataBinder;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import com.googlecode.genericdao.search.Search;

public class FileTypeSelectController extends GenericForwardComposer {

	protected FileTypeService fileTypeService;
	protected FileType selectedFileType;
	protected List<FileType> fileTypes;
	protected Search searchFileType;
	protected AnnotateDataBinder binder;

	public FileTypeService getFileTypeService() {
		return fileTypeService;
	}

	public void setFileTypeService(FileTypeService fileTypeService) {
		this.fileTypeService = fileTypeService;
	}

	public FileType getSelectedFileType() {
		return selectedFileType;
	}

	public void setSelectedFileType(FileType selectedFileType) {
		this.selectedFileType = selectedFileType;
	}

	public List<FileType> getFileTypes() {
		return fileTypes;
	}

	public void setFileTypes(List<FileType> fileTypes) {
		this.fileTypes = fileTypes;
	}

	@Override
	public void doAfterCompose(Component component) throws Exception {
		super.doAfterCompose(component);
		this.searchFileType = new Search(FileType.class);
		this.searchFileType.setMaxResults(100);
		this.searchFileType.addFetch("createdBy");
		this.fileTypes = this.fileTypeService.search(this.searchFileType);
		component.setAttribute("controller", this);
	}

	public void onClick$buttonOk(Event event) throws Exception {
		if (this.selectedFileType != null) {
			this.execution.setAttribute("selectedFileType",
					this.selectedFileType);
			this.execution.setAttribute("result", "ok");
			this.self.detach();
		} else {
			Messagebox.show("Please select a File Type.");
		}
	}

	public void onClick$buttonCancel(Event event) throws Exception {
		this.execution.setAttribute("selectedFileType", null);
		this.execution.setAttribute("result", "cancel");
		this.self.detach();
	}

	public void onClick$buttonSearch(Event event) throws Exception {
		this.execution.setAttribute("searchFileType", this.searchFileType);

		Window window = (Window) this.execution.createComponents(
				"~./zul/html/fileTypeSearch.zul", null, null);
		window.setParent(self);
		window.doModal();

		if (this.execution.getAttribute("result") == "ok") {
			this.searchFileType = (Search) this.execution
					.getAttribute("searchFileType");
		}

		this.fileTypes = this.fileTypeService.search(this.searchFileType);
		this.binder.loadAll();
	}

}
